package com.sanweibook.jhook.web.sys;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanweibook.jhook.common.ErrorCodeEnum;
import com.sanweibook.jhook.common.result.Result;
import com.sanweibook.jhook.common.util.JhookObjectUtils;
import com.sanweibook.jhook.dubbo.dto.sys.SysMenuDTO;
import com.sanweibook.jhook.dubbo.facade.sys.SysMenuFacade;
import com.sanweibook.jhook.web.sys.vo.SysMenuVO;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * Created by twg on 2017/5/14.
 */
@Controller
@RequestMapping("/admin/sys/menu")
public class SysMenuController {
    @Autowired
    private SysMenuFacade sysMenuFacade;

    @RequestMapping
    @RequiresPermissions("sys:menu:list")
    public String list(Model model) {
        SysMenuDTO sysMenuDTO = new SysMenuDTO();
        Result<List<SysMenuDTO>> sysMenuDTOResult = sysMenuFacade.list( sysMenuDTO );
        model.addAttribute( "menus", sysMenuDTOResult.getData() );
        return "sys/menuList";
    }

    @RequestMapping("form")
    @RequiresPermissions(value = {"sys:menu:save", "sys:menu:edit", "sys:menu:view"}, logical = Logical.OR)
    public String form(@RequestParam(value = "id", required = false) Long id, Model model) {
        if (id != null) {
            Result<SysMenuDTO> sysMenuDTOResult = sysMenuFacade.getById( id );
            if (sysMenuDTOResult.isSuccess()) {
                SysMenuDTO sysMenuDTO = sysMenuDTOResult.getData();
                SysMenuVO sysMenuVO = JhookObjectUtils.objectToObject( sysMenuDTO, SysMenuVO.class );
                Result<SysMenuDTO> parentMenuDTOResult = sysMenuFacade.getById( sysMenuVO.getParentId() );
                if (parentMenuDTOResult.isSuccess()) {
                    SysMenuDTO parentMenuDTO = parentMenuDTOResult.getData();
                    SysMenuVO parentMenuVO = JhookObjectUtils.objectToObject( parentMenuDTO, SysMenuVO.class );
                    sysMenuVO.setParentMenu( parentMenuVO );
                }
                model.addAttribute( "menu", sysMenuVO );
            }
        }
        return "sys/menuForm";
    }

    @ResponseBody
    @RequestMapping("saveAndUpdate")
    @RequiresPermissions(value = {"sys:menu:save", "sys:menu:edit"}, logical = Logical.OR)
    public Result<String> saveAndUpdate(@Valid SysMenuVO sysMenuVO, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            return Result.returnErrorResult( ErrorCodeEnum.PARAMETER_ERROR.getCode(), fieldError.getDefaultMessage());
        }
        return sysMenuFacade.saveAndUpdate( JhookObjectUtils.objectToObject( sysMenuVO,SysMenuDTO.class ) );
    }

    @RequiresUser
    @RequestMapping("menuIcon")
    @RequiresPermissions(value = {"sys:menu:save", "sys:menu:edit"}, logical = Logical.OR)
    public String menuIcon(@RequestParam(value = "icon") String icon,Model model){
        model.addAttribute( "icon",icon );
        return "sys/menuIcon";
    }


    @RequiresUser
    @RequestMapping("treeMenu")
    public String treeMenu(@RequestParam(value = "extId") Long extId, Model model) {
        model.addAttribute( "extId", extId );
        return "sys/treeMenu";
    }

    /**
     * 获取json菜单树，默认不包含隐藏的菜单和需要排除的菜单
     *
     * @param extId
     * @return
     */
    @RequiresUser
    @ResponseBody
    @RequestMapping("treeData")
    public Result<List<Map<String, String>>> treeData(@RequestParam(value = "extId", required = false) Long extId) {
        List<Map<String, String>> mapList = Lists.newArrayList();
        Result<List<SysMenuDTO>> listResult = sysMenuFacade.list( new SysMenuDTO() );
        if (listResult.isSuccess()) {
            List<SysMenuDTO> sysMenuDTOS = listResult.getData();
            for (SysMenuDTO sysMenuDTO : sysMenuDTOS) {
                if (isEqual( extId, sysMenuDTO ) || isNoShow( sysMenuDTO )) {
                    continue;
                }
                Map<String, String> map = Maps.newHashMap();
                map.put( "id", sysMenuDTO.getId().toString() );
                map.put( "pId", sysMenuDTO.getParentId().toString() );
                map.put( "name", sysMenuDTO.getMenuName() );
                mapList.add( map );
            }
        }
        return Result.returnSuccessResult( mapList );
    }

    private boolean isNoShow(SysMenuDTO sysMenuDTO) {
        return sysMenuDTO.getIsShow() != null && sysMenuDTO.getIsShow().intValue() != 1;
    }

    private boolean isEqual(Long extId, SysMenuDTO sysMenuDTO) {
        return (extId != null && sysMenuDTO.getId().equals( extId )) || (sysMenuDTO.getParentId().equals( extId ));
    }
}
